<template>
  <div>
    <el-form
      style="margin: 15px 80px;"
      :rules="rules"
      ref="formInline"
      :model="formInline"
      :inline="true"
      class="demo-form-inline demo-ruleForm"
    >
      <el-form-item label="归属系统" prop="systemCode">
        <el-select v-model="formInline.systemCode" placeholder="归属系统">
          <el-option label="user-用户管理系统" value="user"></el-option>
          <el-option label="sales-销售管理系统" value="sales"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="selectMenus('formInline')">查询</el-button>
      </el-form-item>
    </el-form>
    <el-row style="margin: 15px 20px;">
      <el-card class="box-card" style="width: 40%;float: left;">
        <div slot="header" class="clearfix">
          <span>菜单操作</span>
          <el-button style="float: right; padding: 3px 0;" @click="add" type="primary">新增菜单</el-button>
          <el-button
            style="float: right; margin-right:10px;padding: 3px 0"
            @click="delMenu"
            type="danger"
          >删除菜单</el-button>
        </div>
        <div class="text item">
          <el-tree
            :data="systemMenus"
            node-key="id"
            default-expand-all
            @node-click="nodeClick"
            :props="defaultProps"
          ></el-tree>
        </div>
      </el-card>
      <el-card class="box-card" style="width: 55%;float: right;">
        <div slot="header" class="clearfix">
          <span>{{formTile}}</span>
        </div>
        <div class="text item">
          <el-form ref="form" :model="form" label-width="100px">
            <el-form-item label="上级菜单" v-if="upMneu">
              <el-select @change="handleChange" v-model="value" filterable placeholder="新增一级菜单">
                <el-option
                  v-for="item in backMenus"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="菜单名称">
              <el-input v-model="form.name"></el-input>
            </el-form-item>
            <el-form-item label="图标">
              <el-input v-model="form.icon"></el-input>
            </el-form-item>
            <el-form-item label="Path路径">
              <el-input v-model="form.path"></el-input>
            </el-form-item>
            <el-form-item label="默认重定向">
              <el-input v-model="form.redirect"></el-input>
            </el-form-item>
            <el-form-item label="Title标题">
              <el-input v-model="form.title"></el-input>
            </el-form-item>
            <el-form-item label="排序级别">
              <el-input v-model="form.sortId"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="success" :loading="loading" v-if="addBtn" @click="addMenu">新增菜单</el-button>
              <el-button type="primary" :loading="loading" v-if="updateBtn" @click="updateMenu">修改菜单</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
    </el-row>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { addMenu, getSystemMenu, deleteMenu, updateMenu } from "@/api/user";

export default {
  computed: {
    ...mapGetters(["name"])
  },
  data() {
    return {
      thisSystemCode: "user",
      value: "",
      formInline: {
        systemCode: "user"
      },
      systemMenus: [],
      backMenus: [{ id: 0, name: "" }],
      rules: {
        systemCode: [
          { required: true, message: "请选择系统", trigger: "change" }
        ]
      },
      form: {},
      defaultProps: {
        children: "children",
        label: "name"
      },
      upMneu: false,
      addBtn: false,
      updateBtn: false,
      formTile: "修改菜单",
      loading: false
    };
  },
  mounted() {
    this.selectMenus("formInline");
  },
  methods: {
    handleChange(key) {
      this.value = key;
    },
    add() {
      this.value = "新增一级菜单";
      this.upMneu = true;
      this.addBtn = true;
      this.updateBtn = false;
      this.formTile = "新增菜单";
      this.form = {};
      this.$message("请在右边表单中填写相关信息");
    },
    delMenu() {
      if (this.form.path !== "" && this.form.path !== undefined) {
        this.loading = true;
        this.$confirm(
          "此操作将：“" +
            this.form.name +
            "”  菜单删除，以及该菜单下的所有子菜单删除, 是否继续?",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
        )
          .then(() => {
            deleteMenu(this.form.systemCode, this.form.id).then(res => {
              this.$message({
                type: "success",
                message: res.message
              });
              this.loading = false;
              this.selectMenus("formInline");
              this.form = {};
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除"
            });
          });
      } else {
        this.$message({
          type: "warning",
          message: "请选择菜单再点击删除"
        });
      }
    },
    addMenu() {
      if (this.form.redirect == null) this.form.redirect = "";
      const tempValue = this.value;
      let tempValue2 = 0;
      if (tempValue !== "新增一级菜单") tempValue2 = this.value;
      this.loading = true;
      addMenu(
        this.thisSystemCode,
        tempValue2,
        this.form.name,
        this.form.title,
        this.form.path,
        this.form.icon,
        this.form.redirect,
        this.form.sortId
      ).then(res => {
        if (res.message != "success")
          this.$message({
            message: res.message,
            type: "error"
          });
        else {
          this.$message({
            message: "添加菜单成功！",
            type: "success"
          });
          this.selectMenus("formInline");
        }
        this.loading = false;
      });
    },
    updateMenu() {
      console.log(this.value);
      updateMenu(this.form).then(res => {
        this.$message({
          message: res.message,
          type: "success"
        });
      });
    },
    selectMenus(formInline) {
      this.$refs[formInline].validate(valid => {
        if (valid) {
          getSystemMenu(this.formInline.systemCode).then(res => {
            this.thisSystemCode = this.formInline.systemCode;
            this.systemMenus = this.arrayToTree(res.data);
            this.backMenus = res.data;
            this.backMenus.unshift({ id: -1, name: "新增一级菜单" });
          });
        } else {
          this.$message({
            message: "请选择一个系统查询",
            type: "warning"
          });
          return false;
        }
      });
    },
    nodeClick(data) {
      if (data.parentId == 0) this.value = data.id;
      else this.value = data.parentId;
      this.form = data;
      this.addBtn = false;
      this.updateBtn = true;
      this.formTile = "修改菜单";
      this.upMneu = false;
    },
    arrayToTree(list) {
      const data = list;
      const result = [];
      for (let i = 0; i < data.length; i++) {
        delete data[i].children;
      }
      const map = {};
      for (let i = 0; i < data.length; i++) {
        map[data[i].id] = data[i];
      }
      for (let i = 0; i < data.length; i++) {
        const parent = map[data[i].parentId];
        if (parent) {
          (parent.children || (parent.children = [])).push(data[i]);
        } else {
          result.push(data[i]);
        }
      }
      // for (let i = 0; i < result.length; i++) {
      //   result[i].meta = {title: result[i].title, icon: result[i].icon}
      //   if (result[i].hasOwnProperty('children')) {
      //     for (let j = 0; j < result[i].children.length; j++) {
      //       result[i].children[j].meta = {title: result[i].children[j].title, icon: result[i].children[j].icon}
      //     }
      //   }
      // }
      return result;
    }
  }
};
</script>

<style lang="scss" scoped>
</style>
